import 'package:cbec_app/utils/ImageHelper.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class BaseImage extends StatelessWidget {
  ///图片地址(根据传入的url自动使用本地或网络加载)
  final String url;

  ///图片宽度
  final double? width;

  ///图片高度
  final double? height;

  ///适配方式
  final BoxFit fit;

  ///图片灰度颜色
  final Color color;

  ///图片圆角
  final BorderRadiusGeometry borderRadius;

  ///缩放
  final double scale;

  ///基础图片组件
  BaseImage({required this.url, this.width, this.height, this.fit = BoxFit.cover, this.color = Colors.transparent, this.borderRadius = BorderRadius.zero, this.scale = 1});

  @override
  Widget build(BuildContext context) {
    return _getImageWidget();
  }

  ///图片地址
  String get _imageUrl {
    if (url.startsWith('http')) {
      return Uri.encodeFull(url);
    }
    return ImageHelper.wrapAssets(Uri.encodeFull(url));
  }

  ///图片widget
  Widget _getImageWidget() {
    if (url.startsWith('http')) {
      return ClipRRect(
          borderRadius: borderRadius,
          child: Image.network(
            _imageUrl,
            scale: scale,
            width: width,
            height: height,
            color: color,
            colorBlendMode: BlendMode.color,
            fit: fit,
            // loadingBuilder: (context, child, event) {
            //   return ImageHelper.placeHolder(width: width, height: height);
            // },
            errorBuilder: (context, error, stackTrace) {
              logger.d('图片加载错误 $url $error');
              return ImageHelper.error(width: width, height: height, size: width);
            },
          ));
    }
    return ClipRRect(
      borderRadius: borderRadius,
      child: Image.asset(
        _imageUrl,
        scale: scale,
        width: width,
        height: height,
        color: color,
        colorBlendMode: BlendMode.color,
        fit: fit,
        errorBuilder: (context, error, stackTrace) {
          return ImageHelper.error(width: width, height: height, size: width);
        },
      ),
    );
  }
}
